package com.nowcoder.community.actuator;

import com.nowcoder.community.util.CommunityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author szq
 * @create 2023-03-26 2:24
 * @description 性能监控-自定义端点
 */
@Component
@Endpoint(id = "database")
@Slf4j
public class DatabaseEndpoint {

    private DataSource dataSource;

    public DatabaseEndpoint(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    // 读方法
    @ReadOperation
    public String checkConnection() {
        try (Connection connection = dataSource.getConnection();) {
            return CommunityUtil.getJSONString(0,"获取连接成功！");
        } catch (SQLException e) {
            log.error("获取连接失败！");
            return CommunityUtil.getJSONString(1,"获取连接失败！");
        }
    }

    // 写方法
    @WriteOperation
    public void stopConnection(){
        System.out.println("connection close...");
    }
}
